package com.ultimate.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ultimate.management.entity.LoginUser;
import com.ultimate.management.entity.SysMenu;
import com.ultimate.management.entity.SysUser;
import com.ultimate.management.entity.page.PagePara;
import com.ultimate.management.entity.page.PageResultS;
import com.ultimate.management.mapper.SysUserMapper;
import com.ultimate.management.service.SysMenuService;
import com.ultimate.management.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author LH
 * @Date 2024/1/24 8:48
 * @PackageName com.ultimate.management.service.impl
 * @Description: 系统用户判断
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuService sysMenuService;


    public SysUser getUserInfo(String username){
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(SysUser::getUsername,username);
        SysUser sysUser = sysUserMapper.selectOne(lambdaQueryWrapper);
        return sysUser;
    }

    //分页查询所有用户
    @Override
    public PageResultS<SysUser> userData(PagePara pagePara) {
        Page<PagePara> page = new Page<>(pagePara.getPageNo() == null ? 1 : pagePara.getPageNo(),pagePara.getOnePageCount() == null ? 3 : pagePara.getOnePageCount());
        IPage<SysUser> queryResult = sysUserMapper.findAll(page, pagePara);
        PagePara paraResult = new PagePara(queryResult.getCurrent(),queryResult.getSize(),queryResult.getTotal(),queryResult.getPages());
        PageResultS<SysUser> result = new PageResultS<>();
        result.setList(queryResult.getRecords());
        result.setPagePara(paraResult);
        return result;
    }

    //用户状态修改
    @Override
    public int changeStatus(SysUser sysUser) {
        Long userId = sysUser.getUserId();
        if(Objects.isNull(userId)){
           return 0;
        }
        //查询用户信息。我们写的userMapper接口里面是空的，所以调用的是mybatis-plus提供的方法
        LambdaUpdateWrapper<SysUser> queryWrapper = new LambdaUpdateWrapper<>();
        //eq方法表示等值匹配，第一个参数是数据库的用户名，第二个参数是我们传进来的用户名，这两个参数进行比较是否相等
        queryWrapper.eq(SysUser::getUserId,sysUser.getUserId());
        queryWrapper.set(SysUser::getStatus,sysUser.getStatus());
        int update = sysUserMapper.update(null, queryWrapper);
        return update;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息。我们写的userMapper接口里面是空的，所以调用的是mybatis-plus提供的方法
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //eq方法表示等值匹配，第一个参数是数据库的用户名，第二个参数是我们传进来的用户名，这两个参数进行比较是否相等
        queryWrapper.eq(SysUser::getUsername,username);
        SysUser user = sysUserMapper.selectOne(queryWrapper);
        //如果用户传进来的用户名，但是数据库没有这个用户名，就会导致我们是查不到的情况，那么就进行下面的判断。避免程序安全问题
        if(Objects.isNull(user)){//判断user对象是否为空。当在数据库没有查到数据时，user就会为空，也就会进入这个判断
            throw new RuntimeException("用户名或者密码错误");
        }

        //获取用户菜单存入
        List<SysMenu> menuList = sysMenuService.findMenuListById(user.getUserId());
        user.setMenuList(menuList);

        //获取编码权限
        List<String> collect = menuList.stream()
                .filter(item -> item!=null)
                .map(item -> item.getPerms())
                .filter(item -> item!= null)
                .collect(Collectors.toList());
        System.out.println(collect);

        //TODO 查询对应的权限信息
        //把查询到的user结果，封装成UserDetails类型，然后返回。
        //但是由于UserDetails是个接口，所以我们先需要在domino目录新建LoginUser类，作为UserDetails的实现类，再写下面那行

        //转成数组字符串  存入 权限
        String [] Strings = collect.toArray(new String[collect.size()]);
        //设置权限列表
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(Strings);
        LoginUser loginUser = new LoginUser(user, collect);
        loginUser.setAuthorities(authorities);
        return loginUser;
    }
}
